<template>
  <div class="content">
    <sdResult @update:modelValue="handleChildUpdate" @close="showSdResult = false" v-if="showSdResult"
              :open="showSdResult" :rowInfo="rowInfo">
    </sdResult>
    <div class="pageSearchView">
      <el-form :inline="true" :model="searchParam" class="demo-form-inline" label-width="auto" style="width: 100%">
        <el-row>
          <el-col :span="6">
            <el-form-item label="单号">
              <el-input v-model="searchParam.no" placeholder="请输入单号" clearable style="width: 265px"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="来源单号">
              <el-input v-model="searchParam.sourceNo" placeholder="请输入来源单号" clearable style="width: 265px"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="质检类型">
              <el-select v-model="searchParam.qualityType" placeholder="请选择质检类型" clearable style="width: 265px">
                <el-option v-for="(item, index) of qualityTypeList" :key="index" :label="item.label"
                           :value="item.value"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="批次号">
              <el-input v-model="searchParam.batchNo" placeholder="请输入批次号" clearable style="width: 265px"/>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 可展开的检索条件 -->
        <el-collapse-transition>
          <el-row v-if="expandSearch">
            <el-col :span="6">
              <el-form-item label="物料编码">
                <el-input v-model="searchParam.materialNo" placeholder="请输入物料编码" clearable style="width: 265px"/>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="工序名称">
                <el-input v-model="searchParam.procedureName" placeholder="请输入工序名称" clearable style="width: 265px"/>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="机台">
                <el-input v-model="searchParam.deviceCode" placeholder="请输入机台编码" clearable style="width: 265px"/>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="总体数量">
                <el-input v-model="searchParam.batchTotalQuantity" placeholder="请输入总体数量" clearable
                          style="width: 265px"/>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="质检方案名称">
                <el-input v-model="searchParam.name" placeholder="请输入质检方案名称" clearable style="width: 265px"/>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="有效状态">
                <el-select v-model="searchParam.effectiveStatus" placeholder="请选择有效状态" clearable style="width: 265px">
                  <el-option label="无效" :value="0"/>
                  <el-option label="有效" :value="1"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="抽检数量">
                <el-input v-model="searchParam.totalQuantity" placeholder="请输入抽检数量" clearable style="width: 265px"/>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="产品状态">
                <el-select v-model="searchParam.materialStatus" placeholder="请选择有效状态" clearable style="width: 265px">
                  <el-option v-for="(item,index) of materialStatusList" :key="index" :label="item" :value="item"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="委外电镀码">
                <el-input v-model="searchParam.platingCode" placeholder="请输入委外电镀码" clearable style="width: 265px"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="创建时间">
                <el-date-picker
                    v-model="searchParam.createTimeList"
                    type="datetimerange"
                    range-separator="至"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    style="width: 625px"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="特殊放行">
                <el-select v-model="searchParam.isCheck" placeholder="请选择特殊放行" clearable style="width: 265px">
                  <el-option label="是" :value="0"/>
                  <el-option label="否" :value="1"/>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-collapse-transition>

        <!-- 按钮放在最下面，单行且靠右 -->
        <el-row justify="end" style="wid">
          <el-col :span="24" style="text-align: right;">
            <el-form-item>
              <el-button type="primary" :icon="Search" @click="handleSearch()">查询</el-button>
              <el-button class="refreshBtn" :icon="Refresh" @click="resetSearch()">重置</el-button>
              <el-button type="text" @click="expandSearch = !expandSearch">
                {{ expandSearch ? '收起' : '展开' }}
              </el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="pageTableView">
      <div class="pageTableMenuView">
        <div class="pageTableTitle">列表信息</div>
        <div class="pageTableButView">
          <el-button :icon="Tickets" type="primary" :disabled="selectOptions.length < 2 " @click="handleLotEdit()">
            结果批量录入
          </el-button>
          <el-button type="primary" :disabled="selectOptions.length == 0 " @click="handlePrint()">
            标签打印
          </el-button>
          <el-button icon="Delete" type="danger" :disabled="selectOptions.length == 0 " @click="handleLotCancel()">
            批量取消
          </el-button>
          <el-button  type="primary"  :icon="Plus" @click="handleAdd()">新建</el-button>
        </div>
      </div>
      <!-- 表格 多选 -->
      <el-table class="pageTableClass" :data="paginatedData" border :height="tableHeight"
                @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column label="序号" align="center" width="70">
          <template #default="scope"> {{ (pageSearch.current - 1) * pageSearch.pageSize + scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="no" label="单号" align="center" min-width="200"/>
        <el-table-column prop="materialNo" label="物料编码" align="center" min-width="200" show-overflow-tooltip/>
        <el-table-column prop="deviceCode" label="机台" align="center" min-width="200"/>
        <el-table-column prop="batchTotalQuantity" label="总体数量" align="center" min-width="200"/>
        <el-table-column prop="qualityType" label="质检类型" align="center" min-width="200">
          <template #default="scope">
            <span> {{ getQualityTypeByValue(scope.row.qualityType) }} </span></template>
        </el-table-column>
        <el-table-column prop="sourceNo" label="来源单号" align="center" min-width="200"/>
        <el-table-column prop="name" label="质检方案名称" align="center" min-width="250" show-overflow-tooltip/>
        <el-table-column prop="effectiveStatus" label="有效状态" align="center" min-width="200">
          <template #default="scope">
            <span v-if="scope.row.effectiveStatus == 0"> 无效</span>
            <span v-else> 有效</span>
          </template>
        </el-table-column>
        <el-table-column prop="totalQuantity" label="抽检数量" align="center" min-width="200"/>
        <el-table-column prop="batchNo" label="批次号" align="center" min-width="200"/>
        <el-table-column prop="materialStatus" label="产品状态" align="center" min-width="200" show-overflow-tooltip/>
        <el-table-column prop="procedureName" label="工序名称" align="center" min-width="200"/>
        <el-table-column prop="platingCode" label="委外电镀码" align="center" min-width="200"/>
        <el-table-column prop="createTime" label="创建时间" align="center" min-width="200"/>
        <el-table-column prop="isCheck" label="特殊放行" align="center" min-width="200">
          <template #default="scope">
            <span v-if="scope.row.isCheck == 0">是</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" fixed="right" width="230">
          <template #default="scope">
            <el-button @click="handleConfigEdit(scope.row, {},true)" :disabled="scope.row.statusShow"
                       type="warning" size="small" text :icon="DocumentCopy">结果录入
            </el-button>
            <el-dropdown placement="bottom">
              <el-button type="text" size="small" :icon="Switch">操作</el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item key="1" :icon="Edit" :disabled="scope.row.statusShow"
                                    @click="handleEdit(scope.row)">
                    编辑
                  </el-dropdown-item>
                  <!--                  <el-dropdown-item key="2" :icon="Delete" :disabled="scope.row.statusShow" style="color: #F56C6C"-->
                  <!--                                    @click="handleDel(scope.row)">-->
                  <!--                    删除-->
                  <!--                  </el-dropdown-item>-->

                  <el-dropdown-item key="1" :icon="Delete" :disabled="scope.row.statusShow"
                                    @click="handleCancel(scope.row)" v-if="scope.row.effectiveStatus == 1"
                  >
                    取消
                  </el-dropdown-item>
                  <el-dropdown-item key="1" :icon="Files" :disabled="scope.row.statusShow"
                                    @click="release(scope.row,0)" v-if="scope.row.isCheck == 1 && canRelease "
                  >
                    特殊放行
                  </el-dropdown-item>
                  <el-dropdown-item key="1" :icon="Close" :disabled="scope.row.statusShow"
                                    @click="release(scope.row,1)" v-if="scope.row.isCheck == 0 && canRelease"
                  >
                    取消放行
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>

            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagePagination">
        <el-pagination background v-model:current-page="pageSearch.current"
                       v-model:page-size="pageSearch.pageSize" :page-sizes="[10, 20, 50, 100]"
                       layout="total, sizes, prev, pager, next" :total="pageTotal" @size-change="handleSizeChange"
                       @current-change="handleCurrentChange"/>
      </div>
    </div>

    <el-dialog v-model="showCrud" :title="crudTitle" width="900px">
      <el-form :model="formData" label-width="100px" ref="ruleFormRef" :rules="rules" class="demo-ruleForm">
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item required label="来源单号" prop="sourceNo">
              <el-select v-model="formData.sourceNo" placeholder="请选择来源单号" clearable filterable
                         style="width: 300px" :disabled="isEdit" @change="sourceNoChange(true)">
                <el-option v-for="(item, index) of sourceNoList" :key="index" :label="item.workNo"
                           :value="item.workNo"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item required label="质检方案" prop="qualityPlan">
              <el-select v-model="formData.qualityPlan" placeholder="请选择质检方案" clearable filterable
                         style="width: 300px" @change="qualityPlanChange">
                <el-option v-for="(item, index) of qualityPlanList" :key="index" :label="item.name"
                           :value="item.id"/>
              </el-select>
              <!--              <div v-else>{{ formData.name }}</div>-->
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item required label="质检总数" prop="qualityPlan">
              <div>{{ formData.qualityNumber || '-' }}</div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="质检方式" prop="qualityWay">
              <el-select v-model="formData.qualityWay" placeholder="请选择质检方式" clearable
                         style="width: 300px" disabled>
                <el-option v-for="(item, index) of qualityWayList" :key="index" :label="item.label"
                           :value="item.value"/>
              </el-select>
            </el-form-item>
          </el-col>
          <!--					<el-col :span="12">-->
          <!--						<el-form-item label="物料状态" prop="materialStatus">-->
          <!--							<el-select v-model="formData.materialStatus" placeholder="请选择物料状态" clearable-->
          <!--												 style="width: 300px">-->
          <!--								<el-option v-for="(item, index) of materialStatusList" :key="index" :label="item"-->
          <!--													 :value="item" />-->
          <!--							</el-select>-->
          <!--						</el-form-item>-->
          <!--					</el-col>-->
          <el-col :span="12" v-if='formData.qualityType == 1'>
            <el-form-item label="检测原因" prop="qualityReason">
              <el-select v-model="formData.qualityReason" placeholder="请选择检测原因" clearable
                         style="width: 300px">
                <el-option v-for="(item, index) of qualityReasonList" :key="index" :label="item.label"
                           :value="item.value"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if='formData.qualityType == 1'>
            <el-form-item label="生成巡检" prop="isCreateTask">
              <el-switch
                  v-model="formData.isCreateTask"
                  :active-value="true"
                  :inactive-value="false"
              ></el-switch>
            </el-form-item>
          </el-col>
          <!--         -->
          <el-col :span="12" v-if="formData.qualityWay == 2">
            <el-form-item label="比例抽检">
              <el-input-number v-model="formData.proportionNumber" disabled :min="0" :max="1"/>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="formData.qualityWay == 3">
            <el-form-item label="固定抽检">
              <el-input-number v-model="formData.qualityNumber" disabled :step="1" step-strictly
                               :min="0"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="质检类型" prop="qualityType">
              <el-select v-model="formData.qualityType" placeholder="请选择质检类型" clearable
                         style="width: 300px" disabled>
                <el-option v-for="(item, index) of qualityTypeList" :key="index" :label="item.label"
                           :value="item.value"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备编码">
              <el-input v-model="formData.equipmentCode" disabled style="width: 300px"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物料编码">
              <el-input v-model="formData.materialNo" disabled style="width: 300px"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工序名称">
              <el-input v-model="formData.procedureName" disabled style="width: 300px"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12" v-if="formData.qualityType == 4">
            <el-form-item label="巡检间隔" prop="qualityInterval">
              <el-input-number v-model="formData.qualityInterval" :step="0.0001" step-strictly :min="0"
                               disabled/>
              （小时）
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="方案说明" prop="qualityRemark" disabled>
              <el-input v-model="formData.qualityRemark" style="width: 770px" :rows="4" type="textarea"
                        disabled placeholder="请输入方案说明"/>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="formData.qualityType == 4">
            <el-form-item label="下次巡检时间">
              <el-date-picker
                  v-model="formData.nextCreateTime"
                  type="datetime"
                  placeholder="选择"
                  format="YYYY-MM-DD HH:mm:ss"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  date-format="YYYY-MM-DD"
                  time-format="HH:mm:ss"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="formData.qualityType == 4">
            <el-form-item label="终止创建任务">
              <el-switch
                  v-model="formData.isTermination"
                  active-color="#13ce66"
                  inactive-color="#ff4949"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="formData.remark" style="width: 770px" :rows="4" type="textarea"
                        placeholder="请输入备注"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template v-slot:footer>
        <div class="dialog-footer">
          <el-button @click="showCrud = false">取消</el-button>
          <!-- 保存编辑 -->
          <el-button type="primary" @click="handleSave(ruleFormRef)">保存</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="configTableShow" title="质检结果录入" width="95%" top="5vh">
      <el-form :model="schemeTaskForm" label-width="110px" class="demo-ruleForm">
        <el-row :gutter="10">
          <!-- 检验标准录入方式 -->
          <el-col :span="6">
            <el-form-item required label="合格数量">
              <el-input-number v-model="schemeTaskForm.qualifiedQuantity" :step="1" step-strictly
                               :min="0"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item required label="不合格数量">
              <el-input-number v-model="schemeTaskForm.unQualifiedQuantity" :step="1" step-strictly
                               :min="0"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="让步接收数量">
              <el-input-number v-model="schemeTaskForm.compromiseQuantity" :step="1" step-strictly
                               :min="0"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="报废数量">
              <el-input-number v-model="schemeTaskForm.scrapQuantity" :step="1" step-strictly
                               :min="0"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item required label="检验方式">
              <el-select v-model="schemeTaskForm.samplingMethod" placeholder="请选择检验方式"
                         style="width: 300px">
                <el-option label="SPC" value="1"></el-option>
                <el-option label="全尺寸" value="0"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="不良原因" :required="schemeTaskForm.unQualifiedQuantity > 0">
              <el-input v-model="schemeTaskForm.schemeTaskRemark" style="width: 100%" :rows="2"
                        type="textarea" placeholder="请输入不良原因"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row justify="end" style="margin-bottom: 5px">
          <el-button type="danger" :disabled="multipleSelection.length == 0" @click="delMultipleSelection"
                     style="margin-right: 15px">删除质检项
          </el-button>
          <el-upload v-model:file-list="fileList" list-type="xlsx" :show-file-list="false"
                     :before-remove="beforeRemove" :on-exceed="handleExceed"
                     :http-request="customUpload">
            <el-button type="primary">上传解析文件</el-button>
          </el-upload>
          <el-button type="primary" @click="toShowSdResult" style="margin-left: 15px">手动录入</el-button>
          <el-button @click="doCount" style="margin-left: 15px">计算</el-button>
        </el-row>
      </el-form>
      <el-table :data="configTable" height="300px" @selection-change="handleSelectionConfigTable" border
                style="width: 100%">
        <el-table-column type="selection" align="center" width="55"/>
        <el-table-column label="序号" fixed="left" type="index" align="center" width="80"></el-table-column>
        <el-table-column prop="workpieceNumber" fixed="left" align="center" label="抽样编号" min-width="180"
                         show-overflow-tooltip sortable/>
        <el-table-column prop="testitemName" align="center" label="质检项名称" min-width="180"
                         show-overflow-tooltip/>
        <el-table-column prop="testitemType" align="center" label="质检项分类" min-width="180"
                         show-overflow-tooltip/>
        <el-table-column prop="dataType" align="center" label="数值类型" min-width="180" show-overflow-tooltip/>
        <el-table-column prop="judgmentCriteria" align="center" label="检验标准录入方式" min-width="180"
                         show-overflow-tooltip/>
        <el-table-column prop="otherDefect" align="center" label="标准值" min-width="180" show-overflow-tooltip/>
        <el-table-column prop="upperValue" align="center" label="上公差" min-width="180" show-overflow-tooltip/>
        <el-table-column prop="lowerValue" align="center" label="下公差" min-width="180" show-overflow-tooltip/>
        <el-table-column prop="lowerBias" align="center" label="下警戒值" min-width="180" show-overflow-tooltip/>
        <el-table-column prop="upperBias" align="center" label="上警戒值" min-width="180" show-overflow-tooltip/>
        <el-table-column prop="excelCoordinate" align="center" label="SPC坐标" min-width="180"
                         show-overflow-tooltip/>
        <el-table-column prop="defaultValue" align="center" label="检验默认值" min-width="180"
                         show-overflow-tooltip/>
        <el-table-column prop="spcInspection" align="center" label="SPC检" min-width="180"
                         show-overflow-tooltip/>
        <el-table-column prop="fullSizeInspection" align="center" label="全尺寸检" min-width="180"
                         show-overflow-tooltip/>
        <el-table-column prop="fullSizeCoordinate" align="center" label="全尺寸坐标" min-width="180"
                         show-overflow-tooltip/>
        <el-table-column prop="toolCoordinate" align="center" label="量具坐标" min-width="180"
                         show-overflow-tooltip/>
        <el-table-column prop="failNameCode" align="center" label="文件名称代码" min-width="180"
                         show-overflow-tooltip/>
        <el-table-column prop="defectMethod" align="center" label="不良判定方式" min-width="180"
                         show-overflow-tooltip/>
        <el-table-column prop="badReasons" align="center" label="不良原因" min-width="180" show-overflow-tooltip/>
        <el-table-column prop="memo" align="center" label="备注" min-width="180" show-overflow-tooltip/>
        <el-table-column prop="createTime" align="center" label="创建时间" min-width="180" show-overflow-tooltip/>
        <el-table-column prop="realityNumber" align="center" label="实际测量值" min-width="150" fixed="right"
                         show-overflow-tooltip>
          <template #default="scope">
            <el-input v-model="scope.row.realityNumber" placeholder="实际测量值" type="number"
                      style="width: 120px"/>
          </template>
        </el-table-column>
        <el-table-column prop="isQualified" align="center" label="是否合格" min-width="150" fixed="right"
                         show-overflow-tooltip>
          <template #default="scope">
            <el-select v-model="scope.row.isQualified" placeholder="是否合格" clearable style="width: 120px">
              <el-option label="合格" :value="true"/>
              <el-option label="不合格" :value="false"/>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="dataType" align="center" label="不良原因" fixed="right" min-width="200"
                         show-overflow-tooltip>
          <template #default="scope">
            <el-input v-model="scope.row.qualifiedMark" placeholder="请输入不良原因" style="width: 170px"/>
          </template>
        </el-table-column>
        <el-table-column align="center" fixed="right" min-width="100">
          <template #default="scope">
            <el-button type="danger" @click="delLine(scope.row.$index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <template v-slot:footer>
        <div class="dialog-footer">
          <el-button @click="doConfigTableShowClose">关闭</el-button>
          <el-button type="primary" @click="handleSaveConfig">保存</el-button>
        </div>
      </template>
      <!-- 配置质检项 -->
      <el-dialog v-model="showConfig" title="配置质检项" width="1000">
        <el-form :model="configData" label-width="130px" class="demo-ruleForm">
          <el-row :gutter="10">
            <!-- 检验标准录入方式 -->
            <el-col :span="12">
              <el-form-item label="检验标准录入方式" prop="judgmentCriteria">
                <el-input v-model="configData.judgmentCriteria" placeholder="请输入检验标准录入方式"
                          style="width: 300px"/>
              </el-form-item>
            </el-col>
            <!-- 上公差 -->
            <el-col :span="12">
              <el-form-item label="上公差" prop="upperValue">
                <el-input v-model="configData.upperValue" placeholder="请输入上公差" style="width: 300px"/>
              </el-form-item>
            </el-col>
            <!-- 默认值 -->
            <el-col :span="12">
              <el-form-item label="默认值" prop="defaultValue">
                <el-input v-model="configData.defaultValue" placeholder="请输入默认值" style="width: 300px"/>
              </el-form-item>
            </el-col>
            <!-- 下公差 -->
            <el-col :span="12">
              <el-form-item label="下公差" prop="lowerValue">
                <el-input v-model="configData.lowerValue" placeholder="请输入下公差" style="width: 300px"/>
              </el-form-item>
            </el-col>
            <!-- 不良判定方式 -->
            <el-col :span="12">
              <el-form-item label="不良判定方式" prop="defectMethod">
                <el-input v-model="configData.defectMethod" placeholder="请输入不良判定方式"
                          style="width: 300px"/>
              </el-form-item>
            </el-col>
            <!-- 标准值 -->
            <el-col :span="12">
              <el-form-item label="标准值" prop="otherDefect">
                <el-input v-model="configData.otherDefect" placeholder="请输入标准值" style="width: 300px"/>
              </el-form-item>
            </el-col>
            <!-- 备注 -->
            <el-col :span="12">
              <el-form-item label="备注" prop="memo">
                <el-input v-model="configData.memo" placeholder="请输入备注" style="width: 300px"/>
              </el-form-item>
            </el-col>
            <!-- 是否启用 -->
            <el-col :span="12">
              <el-form-item label="是否启用" prop="isEnable">
                <el-input v-model="configData.isEnable" placeholder="请输入是否启用" style="width: 300px"/>
              </el-form-item>
            </el-col>
            <!-- 上警戒值 -->
            <el-col :span="12">
              <el-form-item label="上警戒值" prop="upperBias">
                <el-input v-model="configData.upperBias" placeholder="请输入上警戒值" style="width: 300px"/>
              </el-form-item>
            </el-col>
            <!-- 下警戒值 -->
            <el-col :span="12">
              <el-form-item label="下警戒值" prop="lowerBias">
                <el-input v-model="configData.lowerBias" placeholder="请输入下警戒值" style="width: 300px"/>
              </el-form-item>
            </el-col>
            <!-- SPC坐标 -->
            <el-col :span="12">
              <el-form-item label="SPC坐标" prop="excelCoordinate">
                <el-input v-model="configData.excelCoordinate" placeholder="请输入SPC坐标"
                          style="width: 300px"/>
              </el-form-item>
            </el-col>
            <!-- 全尺寸坐标 -->
            <el-col :span="12">
              <el-form-item label="全尺寸坐标" prop="fullSizeCoordinate">
                <el-input v-model="configData.fullSizeCoordinate" placeholder="请输入全尺寸坐标"
                          style="width: 300px"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="量具坐标" prop="toolCoordinate">
                <el-input v-model="configData.toolCoordinate" placeholder="请输入量具坐标"
                          style="width: 300px"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="SPC检" prop="spcInspection">
                <el-input v-model="configData.spcInspection" placeholder="请输入全尺寸坐标"
                          style="width: 300px"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="全尺寸检" prop="excelCoordinate">
                <el-input v-model="configData.fullSizeInspection" placeholder="请输入全尺寸检"
                          style="width: 300px"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="文件名称" prop="excelCoordinate">
                <el-input v-model="configData.failNameCode" placeholder="请输入文件名称"
                          style="width: 300px"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="数值类型" prop="excelCoordinate">
                <el-input v-model="configData.dataType" placeholder="请输入数值类型" style="width: 300px"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="质检项代码" prop="testitemCode">
                <el-input v-model="configData.testitemCode" placeholder="请输入质检项名称"
                          style="width: 300px"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="质检项名称" prop="excelCoordinate">
                <el-input v-model="configData.testitemName" placeholder="请输入质检项名称"
                          style="width: 300px"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="质检类型" prop="excelCoordinate">
                <el-input v-model="configData.testitemclassificationName" placeholder="质检类型"
                          style="width: 300px"/>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <template v-slot:footer>
          <div class="dialog-footer">
            <el-button @click="showConfig = false">取消</el-button>
            <el-button type="primary" @click="handleSaveConfig">保存</el-button>
          </div>
        </template>
      </el-dialog>
      <el-dialog v-model="showMaterial" title="添加可适用物料" width="500">
        <el-form :model="materialData" label-width="130px" class="demo-ruleForm">
          <el-row :gutter="10">
            <el-form-item label="选择物料">
              <el-select v-model="materialId" placeholder="请选择选择物料" clearable style="width: 300px">
                <el-option v-for="(item, index) of materialList" :key="index" :label="item.materialName"
                           :value="item.id">
                  <span style="float: left">{{ item.materialName }}</span>
                  <span style="
                                    float: right;
                                    color: var(--el-text-color-secondary);
                                    font-size: 13px;
        "> {{ item.materialNo }} </span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-row>
        </el-form>
        <template v-slot:footer>
          <div class="dialog-footer">
            <el-button @click="showMaterial = false">取消</el-button>
            <el-button type="primary" @click="handleSaveMaterial">保存</el-button>
          </div>
        </template>
      </el-dialog>
    </el-dialog>

    <el-dialog v-model="invalidShow" title="取消" width="600">
      <el-form :inline="true" class="demo-form-inline" label-width="80">
        <el-form-item label="原因">
          <!--          <el-select v-model="infoRow.materialinfoStatus" placeholder="请选择" clearable style="width: 265px">-->
          <!--            <el-option v-for="(item, index) of materialStatusLoop" :key="index" :label="item.label"-->
          <!--                       :value="item.value"/>-->
          <!--          </el-select>-->
          <el-input v-model="infoRow.materialinfoStatus" type="textarea" placeholder="请输入取消原因"
                    style="width: 380px"></el-input>
        </el-form-item>

      </el-form>

      <template v-slot:footer>
        <div class="dialog-footer">
          <el-button @click="invalidShow = false">取消</el-button>
          <!-- 保存编辑 -->
          <el-button type="primary" @click="saveQu">保存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import axiosInstance from '@/utils/http/api';
import {
  Delete,
  DocumentCopy,
  Switch,
  Edit,
  Plus,
  Refresh,
  Search,
  Tickets,
  Files,
  Close
} from '@element-plus/icons-vue';
import type {FormInstance, FormRules} from 'element-plus';
import {ElMessage, ElMessageBox} from 'element-plus';
import {h, computed, reactive, ref, getCurrentInstance} from 'vue';
import sdResult from './sdresult.vue';
import moment from 'moment';

const handleChildUpdate = (newValue) => {
  console.log(newValue, 'handleChildUpdate');
  showSdResult.value = false;
  finalSaveData.value = newValue.list;
  configTable.value = newValue.list;
};
const showSdResult = ref(false);
const toShowSdResult = () => {
  // configTableShow.value = false
  showSdResult.value = true;
};
import {RouterView, useRoute} from 'vue-router';

const route = useRoute();

onMounted(() => {
  searchParam.value.no = route.query.no;
  handleSearch();
  getOptions();
});
// 文件上传
const finalResult = ref([]);
const fileList = ref([]);
const finalSaveData = ref([]);
const customUpload = async ({file, data}) => {
  console.log(formData.samplingMethod);
  const formDataResult = new FormData();
  formDataResult.append('file', file); // 确保 file 是 Blob 类型
  formDataResult.append('id', rowInfo.value.id); // id 是字符串，可以正常传递
  formDataResult.append('methods', schemeTaskForm.value.samplingMethod); // id 是字符串，可以正常传递
  try {
    axiosInstance.post('/api/fileUpload/uploadAndParse', formDataResult).then(async res => {
      if (res.code == 200) {
        // fileList.value = [];
        const data = JSON.parse(res.data);
        data.finalGroupedDataArray = data.finalGroupedDataArray.map(item => {
          console.log(item);

          if (schemeTaskForm.value.samplingMethod == 1) {
            item.excelCoordinate = item.coordinate;
            item.fullSizeCoordinate = '';
          } else {
            item.fullSizeCoordinate = item.coordinate;
            item.excelCoordinate = '';
          }
          return item;
        });
        // 将新解析的数据合并到 finalResult
        finalResult.value = finalResult.value.concat(data.finalGroupedDataArray);
        // workpieceNumber抽样编号
        // 按 workpieceNumber 分组并相加
        const groupedData = [];
        const map = new Map();

        finalResult.value.forEach(item => {
          if (!map.has(item.workpieceNumber)) map.set(item.workpieceNumber, []);
          map.get(item.workpieceNumber).push(item);
        });

        // 将 Map 中的数据推入 groupedData
        map.forEach(items => {
          groupedData.push(...items);
        });

        console.log('按编号合并并分组后的数组：', groupedData);
        handleConfigEdit(rowInfo.value, {finalGroupedDataArray: finalResult.value});
        finalSaveData.value = finalSaveData.value.concat(groupedData);

        ElMessage.success('文件解析成功!');
      } else {
        fileList.value = [];
      }
    });
  } catch (error) {
    console.error('上传失败:', error);
  }
};


const handleExceed = (files, uploadFiles) => {
  ElMessage.warning(
      `The limit is 3, you selected ${files.length} files this time, add up to ${files.length + uploadFiles.length
      } totally`
  );
};

const beforeRemove = (uploadFile, uploadFiles) => {
  return ElMessageBox.confirm(
      `Cancel the transfer of ${uploadFile.name} ?`
  ).then(
      () => true,
      () => false
  );
};

const qualityPlanList = ref({});
const sourceNoList = ref([]);
const getOptions = () => {
  // axiosInstance.post('/api/basedataQualityScheme/getAll', {})
  // 	.then(res => {
  // 		if (res.code !== 200) {
  // 			ElMessage.error(res.message);
  // 			return false;
  // 		}
  // 		qualityPlanList.value = res.data;
  // 	});

  axiosInstance.post('/api/workOrder/getAll', {})
      .then(res => {
        if (res.code !== 200) {
          ElMessage.error(res.message);
          return false;
        }
        sourceNoList.value = res.data;
      });

};

const materialStatusLoop = ref([
  {
    label: '工单结束',
    text: '工单结束',
    value: '工单结束'
  },
  {
    label: '调机/停机',
    text: '调机/停机',
    value: '调机/停机'
  },
  {
    label: '任务创建错误',
    text: '任务创建错误',
    value: '任务创建错误'
  }
]);


const pageSearch = ref({
  current: 1,
  pageSize: 10
});

const schemeTaskForm = ref({
  samplingMethod: '1'
});

const configTableShow = ref(false);


// 配置质检项表
const configTable = ref([]);

// 可适用物料
const materialTable = ref([]);


const rowInfo = ref({});


// 结果录入
const handleConfigEdit = (row: any, data, clearn) => {
  console.log(row, data);
  rowInfo.value = row;

  if (Array.isArray(data?.finalGroupedDataArray)) {
    configTable.value = [...data?.finalGroupedDataArray, ...configTable.value];
    // 接下来，根据isQualified属性对数组进行排序
    configTable.value.sort((a, b) => {
      // 如果a和b都是isQualified为true，或者都是isQualified为false，保持它们的位置不变
      if ((a.isQualified && b.isQualified) || (!a.isQualified && !b.isQualified)) {
        return 0;
      }
      // 如果a是isQualified为true，而b是isQualified为false，将a排在b后面
      if (a.isQualified && !b.isQualified) {
        return 1;
      }
      // 如果a是isQualified为false，而b是isQualified为true，将a排在b前面
      return -1;
    });
  } else {
    if (clearn) {
      configTable.value = [];
      schemeTaskForm.value.schemeTaskRemark = null
    }
    // 处理错误情况，例如设置一个默认值或者显示错误信息
  }

  doCount();

  // configTable.value = data?.finalGroupedDataArray;
  fileList.value = [];
  finalResult.value = [];
  configTableShow.value = true;
  // schemeTaskForm.value = {};
  // showSdResult.value = false;
};

const doCount = () => {
  let unqualifiedCount = 0;
  let qualifiedCount = 0;
  const workpieceNumbers = new Set(); // 用于存储已经检查过的workpieceNumber


  // realityNumber 实际测量值
  // otherDefect 标准值
  // upperValue 上公差
  // lowerValue 下公差
  // isQualified 是否合格

  configTable.value.forEach(item => {

    const standardUpperValue = Number(item.otherDefect) + Number(item.upperValue);
    const standardLowerValue = Number(item.otherDefect) + Number(item.lowerValue);

    // 判断实际测量值是否在标准值的上下公差范围内
    if (item.dataType == '数字') {
      item.isQualified = Number(item.realityNumber) >= standardLowerValue && Number(item.realityNumber) <= standardUpperValue;
    }

    // 如果该workpieceNumber尚未被检查过
    if (!workpieceNumbers.has(item.workpieceNumber)) {
      workpieceNumbers.add(item.workpieceNumber); // 标记为已检查
      // 检查该产品的所有记录是否至少有一个不合格
      const isWorkpieceQualified = configTable.value.every(
          record => record.workpieceNumber === item.workpieceNumber ? record.isQualified : true
      );
      // 如果至少有一个不合格，则增加不合格计数
      if (!isWorkpieceQualified) {
        unqualifiedCount++;
      } else {
        qualifiedCount++; // 否则，增加合格计数
      }
    }
  });

  schemeTaskForm.value.unQualifiedQuantity = unqualifiedCount;
  schemeTaskForm.value.qualifiedQuantity = qualifiedCount;
};

const ids = ref([]);

const handleLotEdit = () => {
  const qualityType = selectOptions.value[0].qualityType;
  const platingCode = selectOptions.value[0].platingCode;
  ids.value = [];
  const isValid = selectOptions.value.some(item => {
    if (item.qualityType !== qualityType || item.platingCode !== platingCode) {
      ElMessage.error('请选择相同类型的委外电镀和质检类型');
      return true;
    }
    ids.value.push(item.id);
    return false;
  });
  if (!isValid) {
    rowInfo.value = selectOptions.value[0];
    configTableShow.value = true;
  }
};


const materialList = ref({});
const selectOptions = ref([]);
const handleSelectionChange = (e) => {
  selectOptions.value = e;
};


const sourceNoChange = (clearn) => {
  let param = sourceNoList.value.find(item => item.workNo == formData.value.sourceNo);
  console.log(param);
  formData.value.materialId = param.materialId;
  formData.value.equipmentCode = param.equipmentCode;
  formData.value.materialNo = param.materialNo;
  formData.value.procedureName = param.procedureName;
  formData.value.orderCount = param.orderCount ? param.orderCount : 0;
  formData.value.qualityNumber = formData.value.orderCount
  qualitySchemeByWorkNo(formData.value.sourceNo, formData.value.materialId, clearn)
};

const qualitySchemeByWorkNo = (no, mId, clearn) => {
  // no 来源单号 mId物料id clearn 是否清空

  axiosInstance.get('/api/qualitySchemeTask/qualitySchemeByWorkNo', {params: {workNo: no, materialId: mId}})
      .then(res => {
        if (res.code !== 200) {
          ElMessage.error(res.message);
          return false;
        }
        qualityPlanList.value = res.data;
        if (clearn) {
          formData.value.qualityPlan = null;
        }
        //
      });
}

const qualityPlanChange = (e) => {
  let param = qualityPlanList.value.find(item => item.id == e);
  let json = JSON.parse(param.qualityJson);
  formData.value.qualityWay = json.qualityWay;
  formData.value.qualityType = json.qualityType;
  formData.value.proportionNumber = json.proportionNumber;
  if (formData.value.qualityWay == 1) {
    formData.value.qualityNumber = formData.value.orderCount
  } else if (formData.value.qualityWay == 2) {
    formData.value.qualityNumber = (formData.value.orderCount * json.proportionNumber).toFixed(0);
  } else if (formData.value.qualityWay == 3) {
    formData.value.qualityNumber = json.qualityNumber;
  }
  formData.value.batchTotalQuantity = json.qualityNumber;
  formData.value.totalQuantity = json.qualityNumber;
  formData.value.qualityInterval = json.qualityInterval;
  formData.value.qualityRemark = json.qualityRemark;
  json.qualityPlan = e;
  json.qualityPlanName = param.name;
  formData.value.qualityJson = JSON.stringify(json);
};


const materialData = ref({});
const showMaterial = ref(false);

// 通用更新接口函数
const handleUpdateQualityScheme = (updatedRowInfo) => {
  axiosInstance.put('/api/qualitySchemeTask/update', updatedRowInfo).then(res => {
    if (res.code != 200) {
      ElMessage.error(res.message);
      return false;
    }
    ElMessage.success('操作成功!');
    configTableShow.value = false;
    // 刷新配置质检项列表
    handleSearch();
  });
};


const {proxy}: any = getCurrentInstance();
const handlePrint = () => {
  console.log(selectOptions.value);
  const templateName = 'test_print1/QualitySchemeTaskPrint.cpt';
  proxy.$printClick(templateName, selectOptions.value);
};

const expandSearch = ref(false); // 控制检索条件的展开和收起

const materialId = ref(null);
// 报错适配物料
const handleSaveMaterial = () => {
  const jsonParam = JSON.parse(rowInfo.value.qualityJson);
  for (const item of materialTable.value) {
    if (item.id == materialId.value) {
      ElMessage.error('该物料已存在');
      return false;
    }
  }
  let param = ref({});
  for (const items of materialList.value) {
    if (items.id == materialId.value) {
      param = items;
    }
  }
  // 保存
  // 存在则push
  if (jsonParam.materialTable && jsonParam.materialTable.length) {
    jsonParam.materialTable.unshift(param);
  } else {
    // 不存在则创建
    jsonParam.materialTable = [param];

  }

  rowInfo.value.qualityJson = JSON.stringify(jsonParam);
  handleUpdateQualityScheme(rowInfo.value);
};

const roleRouteList = ref([]);
const roleRoute = ref(localStorage.getItem('roleRouteList') || '[]'); // 默认为空数组字符串
try {
  roleRouteList.value = JSON.parse(roleRoute.value);
} catch (error) {
  roleRouteList.value = []; // 设置为空数组或者其他默认值
}
const canRelease = computed(() => {
  // 使用计算属性来检查是否有urlPath为'release'的项
  return roleRouteList.value.some(item => item.urlPath === 'release');
});

// release


// 质检项表删除 新建 编辑
const handleSaveConfig = () => {
  const jsonParam = JSON.parse(rowInfo.value.qualityJson);
  if (schemeTaskForm.value.qualifiedQuantity === undefined || schemeTaskForm.value.qualifiedQuantity === null || schemeTaskForm.value.qualifiedQuantity === '') {
    ElMessage.error('请输入合格数量');
    return false;
  }

  if (!schemeTaskForm.value.unQualifiedQuantity && schemeTaskForm.value.unQualifiedQuantity != 0) {
    ElMessage.error('请输入不合格数量');
    return false;
  }
  if (schemeTaskForm.value.unQualifiedQuantity != 0 && !schemeTaskForm.value.schemeTaskRemark) {
    ElMessage.error('请输入不良原因');
    return false;
  }
  if (!schemeTaskForm.value.samplingMethod) {
    ElMessage.error('请选择检验方式');
    return false;
  }

  if (schemeTaskForm.value.unQualifiedQuantity > 0) {
    ElMessageBox.confirm(
        '存在不合格数据，是否继续提交?',
        '提示',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'error'
        }
    ).then(() => {
      doP();
    });
  } else {
    doP();
  }

  function doS() {
// 提交
    jsonParam.schemeTaskForm = schemeTaskForm.value;
    // jsonParam.configTable = finalSaveData.value;
    // jsonParam.schemeTaskForm.configTable = finalSaveData.value;
    jsonParam.configTable = configTable.value;
    jsonParam.schemeTaskForm.configTable = configTable.value;
    delete jsonParam.qualityJson;

    rowInfo.value.status = true;
    rowInfo.value.schemeTaskForm = schemeTaskForm.value;

    rowInfo.value = {
      ...jsonParam,
      ...rowInfo.value,
      qualityJson: JSON.stringify(jsonParam)
    };
    if (ids.value.length > 0) {
      rowInfo.value.batchUpdateIds = ids.value;
    }
    console.log(rowInfo.value);
    handleUpdateQualityScheme(rowInfo.value);

  }

  function doP() {
    // 获取当前检验类型配置
    const isSPCMode = schemeTaskForm.value.samplingMethod === '1';

    const inspectionType = isSPCMode ? 'spcInspection' : 'fullSizeInspection';

    console.log(inspectionType, 'inspectionType spcInspection , fullSizeInspection')

    // 获取需要检测的缺陷代码集合（带检验类型过滤）
    const requiredCodes = new Set();
    rowInfo.value.configTable.forEach(item => {
      // 双重验证：必须同时满足条件
      if (item.failNameCode && item[inspectionType] === '是') {
        requiredCodes.add(item.failNameCode);
      }
    });

    console.log(requiredCodes, 'requiredCodes')

    // 获取实际配置的缺陷代码集合
    const configuredCodes = new Set(
        configTable.value
            .map(item => item.failNameCode)
            .filter(Boolean)
    );

    console.log(configuredCodes, 'configuredCodes')

    // 计算缺失的缺陷代码（带检验类型需求）
    const missingCodes = [];
    requiredCodes.forEach(code => {
      if (!configuredCodes.has(code)) {
        missingCodes.push(code);
      }
    });
    console.log(missingCodes, 'missingCodes')
    // 异常处理流程
    if (missingCodes.length > 0) {
      const confirmMessage = `缺少${isSPCMode ? 'SPC' : '全尺寸'}检测文件名称代码:
${missingCodes.join(', ')}`;

      ElMessageBox.confirm(confirmMessage, '提示', {
        confirmButtonText: '继续操作',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: true
      }).then(doS).catch(() => {
        // ElMessage.warning('已中止当前操作');
      });
    } else {
      doS();
    }
  }

};


const pageTotal = ref(null);//页面总数
const isEdit = ref(false); // 是否编辑
const showCrud = ref(false); // 编辑/新建弹框
const searchParam = ref({});//页面检索条件
const showConfig = ref(false);
const configData = ref({});
const crudTitle = computed(() => {
  return isEdit.value ? '编辑' : '新建';
});//弹出层标题

// 质检方式
const qualityWayList = reactive([
  {
    label: '全检',
    value: '1'
  }, {
    label: '比例抽检',
    value: '2'
  }, {
    label: '固定抽检',
    value: '3'
  }, {
    label: '自定义抽检',
    value: '4'
  }
]);


const tableHeight = computed(() => {
  return expandSearch.value ? 'calc(100vh - 520px)' : 'calc(100vh - 370px)';
});

const materialStatusList = ref([
  '正常品', '素材不良', '制程报废'
]);

//0123开机，调机，调模，换班 
const qualityReasonList = ref([
  {
    label: '开机',
    value: 0
  },
  {
    label: '调机',
    value: 1
  },
  {
    label: '调模',
    value: 2
  },
  {
    label: '换班',
    value: 3
  }
]);


// 判断质检类型
const getQualityTypeByValue = (e) => {
  let name = null;
  for (const item of qualityTypeList) {
    if (e == item.value) {
      name = item.label;
    }
  }
  return name;
};

// 质检类型
const qualityTypeList = reactive([
  {
    label: '首件检',
    value: '1',
    type: 'procedure'
  },
  {
    label: '末件检',
    value: '2',
    type: 'procedure'
  },
  {
    label: '生产',
    value: '3',
    type: 'procedure'
  },
  {
    label: '巡检',
    value: '4',
    type: 'procedure'
  },
  {
    label: '入库检',
    value: '5',
    type: 'material'
  },
  {
    label: '出库检',
    value: '6',
    type: 'material'
  },
  {
    label: '来料检',
    value: '7',
    type: 'material'
  }
]);

const ruleFormRef = ref<FormInstance>();

interface RuleForm {
  name: string;
  code: string;
  qualityWay: string;
  proportionNumber: string;
  qualityNumber: string;
  qualityType: string;
  qualityInterval: number;
  qualityIsLive: boolean;
  qualityRemark: string;
  qualityJson: string;
}


let formData = ref({});


const rules = reactive<FormRules<formData>>({
  sourceNo: [
    {required: true, message: '请输入来源单号', trigger: 'blur'}
  ],
  qualityPlan: [
    {required: true, message: '请选择质检方案', trigger: 'blur'}
  ],
  samplingMethod: [
    {required: true, message: '请选择质检方式', trigger: 'blur'}
  ]
});


const paginatedData = ref<RuleForm[]>([]);

// 获取列表接口
const handleSearch = async () => {
  await axiosInstance.post('/api/qualitySchemeTask/getPage', {
    ...searchParam.value,
    ...pageSearch.value,
    ...{
      status: false
    }
  })
      .then(res => {
        if (res.code !== 200) {
          ElMessage.error(res.message);
          return false;
        }
        const loop = res.data.records;
        const dataLoop = [];
        for (const item of loop) {
          let list = {};
          if (item.qualityJson) {
            list = JSON.parse(item.qualityJson);
          }
          item.statusShow = item.status;
          list = {...list, ...item};
          dataLoop.push(list);
        }
        paginatedData.value = dataLoop;
        console.log(dataLoop, 'dataLoop');
        pageTotal.value = res.data.total;
      });
};

const multipleSelection = ref([]);

const handleSelectionConfigTable = (val) => {
  multipleSelection.value = val;
};

const delLine = (index) => {
  ElMessageBox.confirm(
      '确认删除该条数据吗?',
      '提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'error'
      }
  ).then(() => {
    configTable.value.splice(index, 1);
  });
};
const delMultipleSelection = () => {
  ElMessageBox.confirm(
      '确认删除选中的质检项吗?',
      '提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'error'
      }
  ).then(() => {
    // 创建一个副本以避免在遍历过程中修改数组
    const selectedItems = [...multipleSelection.value];
    // 遍历选中的项
    selectedItems.forEach((selectedItem) => {
      // 构建唯一值
      const uniqueValue = `${selectedItem.workpieceNumber}-${selectedItem.testitemName}`;
      // 查找configTable中匹配的项
      const index = configTable.value.findIndex(item => `${item.workpieceNumber}-${item.testitemName}` === uniqueValue);
      if (index > -1) {
        // 如果找到了，则从configTable中移除
        configTable.value.splice(index, 1);
      }
    });
  });
};

const handleSizeChange = (e) => {
  pageSearch.value.pageSize = e;
  handleSearch();
};

const handleCurrentChange = (e) => {
  pageSearch.value.current = e;
  handleSearch();
};

// 重置搜索条件
const resetSearch = () => {
  searchParam.value = {};
  pageSearch.value.current = 1;
  handleSearch();
};

// 点击新建
const handleAdd = () => {
  isEdit.value = false;
  // ruleFormRef.value.resetFields()
  formData.value = {nextCreateTime: moment().add(2, 'hours').format('YYYY-MM-DD HH:mm:ss'), isCreateTask: true};
  qualityPlanList.value = [];
  showCrud.value = true;
};

// 特殊放行
const release = (row, val) => {
  ElMessageBox.confirm('是否放行该条记录？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    let param = JSON.parse(JSON.stringify(row));
    param.isCheck = val;
    axiosInstance.put(`/api/qualitySchemeTask/update`, param).then(res => {
      ElMessage.success('操作成功');
      handleSearch(); // 刷新数据
    });


  });
};
// 编辑
const handleEdit = (row: any) => {
  console.log(row)
  isEdit.value = true;
  const param = JSON.parse(row.qualityJson);
  formData.value = row;
  formData.value.qualityPlan = param.qualityPlan;
  // sourceNoChange();
  qualitySchemeByWorkNo(row.sourceNo, row.materialId)
  showCrud.value = true;
};


const selectedReason = ref(''); // 用于存储选中的无效原因

const infoRow = ref({});
const invalidShow = ref(false);
const handleCancel = (row) => {
  infoRow.value = {list: [row]}
  invalidShow.value = true;
};

const handleLotCancel = () => {
  if (selectOptions.value.find(item => item.effectiveStatus != 1)) {
    ElMessage.error('无效状态任务不可以取消');
    return false;
  }
  infoRow.value = {list: selectOptions.value}
  invalidShow.value = true;
}

const saveQu = () => {
  axiosInstance.post('/api/qualitySchemeTask/invalid', {
    ids: infoRow.value.list.map(item => item.id),
    invalidReason: infoRow.value.materialinfoStatus
  }).then(res => {
    if (res.code !== 200) {
      ElMessage.error(res.message);
      return false;
    }
    invalidShow.value = false;
    ElMessage.success('操作成功');
    handleSearch();
  });
};

// 删除记录
const handleDel = (row: any) => {
  ElMessageBox.confirm('确定删除该条记录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    axiosInstance.delete(`/api/qualitySchemeTask/delete`, {
      data: {
        ids: [row.id]
      }
    }).then(res => {
      ElMessage.success('删除成功');
      handleSearch(); // 刷新数据
    });
  });
};


const doConfigTableShowClose = () => {
  configTableShow.value = false;
  configTable.value = [];
  finalSaveData.value = []; // 新增：清空缓存数据
  fileList.value = [];
};

// 弹框确定 确认新建 确定编辑
const handleSave = async (e: FormInstance | undefined) => {
  if (!e) return;
  await e.validate((valid, fields) => {
    if (valid) {
      if (formData.value.qualityType == 4 && !formData.value.isTermination) {
        // 检查下次创建时间是否已选择
        if (!formData.value.nextCreateTime) {
          ElMessage.error('请选择下次创建时间');
          return false;
        }
        // 检查下次创建时间是否晚于当前时间
        const nextCreateTimeMoment = moment(formData.value.nextCreateTime, 'YYYY-MM-DD HH:mm:ss');
        if (!nextCreateTimeMoment.isValid() || nextCreateTimeMoment.isBefore(moment())) {
          ElMessage.error('下次创建时间不能早于现在');
          return false;
        }
      }
      formData.value.name = qualityPlanList.value.find(item => item.id == formData.value.qualityPlan).name
      const jsonString = JSON.parse(formData.value.qualityJson);
      jsonString.qualityReason = formData.value.qualityReason;
      jsonString.qualityPlan = formData.value.qualityPlan;
      formData.value.qualityJson = JSON.stringify(jsonString);
      if (isEdit.value) {
        // 编辑
        // const jsonString = JSON.stringify(formData.value);
        // formData.qualityJson = jsonString;
        axiosInstance.put('/api/qualitySchemeTask/update', formData.value).then(res => {
          if (res.code != 200) {
            ElMessage.error(res.message);
            return false;
          }
          ElMessage.success('操作成功!');
          showCrud.value = false;
          handleSearch(); // 刷新数据
        });
      } else {
        // 新建
        // {
        //   label: '全检',
        //       value: '1'
        // }, {
        //   label: '比例抽检',
        //       value: '2'
        // }, {
        //   label: '固定抽检',
        //       value: '3'
        // }, {
        //   label: '自定义抽检',
        //       value: '4'
        // }
        const paramData = {...formData.value};
        paramData.id = null;
        paramData.status = false;
        let url = '/api/qualitySchemeTask/createMaterialTask';
        if (paramData.qualityType == 1 || paramData.qualityType == 2 || paramData.qualityType == 3 || paramData.qualityType == 4) {
          url = '/api/qualitySchemeTask/createWorkOrderTask';
        }
        axiosInstance.post(url, paramData).then(res => {
          if (res.code != 200) {
            ElMessage.error(res.message);
            return false;
          }
          ElMessage.success('操作成功!');
          showCrud.value = false;
          handleSearch(); // 刷新数据
        });
      }

    }
  });
};

</script>
